using System;
using UnityEngine;

public class JNIHelper
{
    public static byte[] GetAsset(string filePath)
    {
        // Activity for Achieving Applications
        var activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
        // Get an AssetManager instance from Activity
        var assetManager = activity.Call<AndroidJavaObject>("getAssets");

        // Open the file stream
        var stream = assetManager.Call<AndroidJavaObject>("open", filePath);
        // Get file length
        var availableBytes = stream.Call<int>("available");

        // Get the MethodID of InputStream. read
        var cls = new AndroidJavaClass("java.io.InputStream");
        var METHOD_read = AndroidJNIHelper.GetMethodID(cls.GetRawClass(), "read", "([B)I");

        // Apply for a Java ByteArray object handle
        var byteArray = AndroidJNI.NewByteArray(availableBytes);
        // Call method
        int readCount = AndroidJNI.CallIntMethod(stream.GetRawObject(), METHOD_read, new[] { new jvalue() { l = byteArray } });
        // Get the C byte array from Java ByteArray
        var bytes = AndroidJNI.FromByteArray(byteArray);
        // Delete Java ByteArray object handle
        AndroidJNI.DeleteLocalRef(byteArray);
        // Close the file stream
        stream.Call("close");
        stream.Dispose();
        // Return results
        byte[] bs = new byte[bytes.Length];
        Buffer.BlockCopy(bytes, 0, bs, 0, bytes.Length);
        return bs;
    }
}